import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const dataDir = path.join(__dirname, '..', 'data');

// 读取数据文件
function readJSONFile(filename) {
    const filePath = path.join(dataDir, filename);
    try {
        const content = fs.readFileSync(filePath, 'utf8');
        return JSON.parse(content);
    } catch (error) {
        console.error(`读取文件失败 ${filename}:`, error);
        return [];
    }
}

// 写入数据文件
function writeJSONFile(filename, data) {
    const filePath = path.join(dataDir, filename);
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
    console.log(`✓ 已更新 ${filename}`);
}

// 生成用户名（从姓名或手机号）
function generateUsername(name, phone, existingUsernames) {
    // 尝试使用姓名（去除特殊字符）
    const cleanName = name.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, '');

    // 如果姓名是英文且长度合适，使用姓名
    if (/^[a-zA-Z]+$/.test(cleanName) && cleanName.length >= 2 && cleanName.length <= 20) {
        let username = cleanName.toLowerCase();
        let counter = 1;
        while (existingUsernames.includes(username)) {
            username = `${cleanName.toLowerCase()}${counter}`;
            counter++;
        }
        return username;
    }

    // 否则使用手机号生成
    let username = `student_${phone.slice(-6)}`;
    let counter = 1;
    while (existingUsernames.includes(username)) {
        username = `student_${phone.slice(-6)}_${counter}`;
        counter++;
    }
    return username;
}

async function fixUserAccounts() {
    console.log('开始修复学生账号...\n');

    // 读取现有数据
    const users = readJSONFile('users.json');
    const students = readJSONFile('students.json');
    const roles = readJSONFile('roles.json');
    const userRoles = readJSONFile('userRoles.json');

    // 获取角色ID
    const studentRoleId = roles.find(r => r.code === 'student')?.id;
    const teacherRoleId = roles.find(r => r.code === 'teacher')?.id;

    // 获取现有用户名
    const existingUsernames = users.map(u => u.username);

    // 创建phone到user的映射（排除教师账号）
    const phoneToUser = {};
    users.forEach(user => {
        if (user.phone) {
            // 如果该用户已经是教师角色，不要覆盖
            const isTeacher = userRoles.some(ur => ur.userId === user.id && ur.roleId === teacherRoleId);
            if (!isTeacher || !phoneToUser[user.phone]) {
                phoneToUser[user.phone] = user;
            }
        }
    });

    let newUserCount = 0;
    let newUserRoleCount = 0;
    let maxUserId = Math.max(...users.map(u => u.id), 0);
    let maxUserRoleId = userRoles.length > 0 ? Math.max(...userRoles.map(ur => ur.id), 0) : 0;

    // 为学生创建账号
    console.log('处理学生账号...');
    students.forEach(student => {
        if (!student.phone) {
            console.log(`  ⚠️  跳过学生 ${student.name} (ID: ${student.id})，没有手机号`);
            return;
        }

        let user = phoneToUser[student.phone];

        // 检查该用户是否已经是教师
        if (user) {
            const userRole = userRoles.find(ur => ur.userId === user.id && ur.roleId === teacherRoleId);
            if (userRole) {
                console.log(`  ⚠️  手机号 ${student.phone} 已被教师账号 ${user.username} 使用，为学生 ${student.name} 创建新账号`);
                user = null; // 强制创建新账号
            }
        }

        if (!user) {
            // 创建新用户
            maxUserId++;
            const username = generateUsername(student.name, student.phone, existingUsernames);
            user = {
                id: maxUserId,
                username: username,
                password: '123456', // 默认密码
                email: student.email || `${username}@school.edu`,
                phone: student.phone,
                role: 'student', // 保留旧字段以兼容
                avatar: null,
                createdAt: new Date().toISOString(),
                lastLogin: null
            };
            users.push(user);
            existingUsernames.push(username);
            phoneToUser[student.phone] = user;
            newUserCount++;
            console.log(`  ✓ 创建学生账号: ${username} (phone: ${student.phone}, name: ${student.name})`);
        } else {
            console.log(`  - 学生账号已存在: ${user.username} (phone: ${student.phone})`);
        }

        // 检查是否已有学生角色关联
        const existingRole = userRoles.find(ur => ur.userId === user.id && ur.roleId === studentRoleId);
        if (!existingRole) {
            maxUserRoleId++;
            userRoles.push({
                id: maxUserRoleId,
                userId: user.id,
                roleId: studentRoleId,
                createdAt: new Date().toISOString()
            });
            newUserRoleCount++;
            console.log(`    ✓ 添加学生角色关联`);
        }

        // 移除错误的学生角色关联（如果用户是教师，不应该有学生角色）
        const teacherRole = userRoles.find(ur => ur.userId === user.id && ur.roleId === teacherRoleId);
        if (teacherRole) {
            const wrongStudentRole = userRoles.find(ur => ur.userId === user.id && ur.roleId === studentRoleId);
            if (wrongStudentRole) {
                const index = userRoles.indexOf(wrongStudentRole);
                userRoles.splice(index, 1);
                console.log(`    ⚠️  移除错误的学生角色关联（该用户是教师）`);
            }
        }
    });

    // 保存更新后的数据
    console.log('\n保存数据...');
    writeJSONFile('users.json', users);
    writeJSONFile('userRoles.json', userRoles);

    console.log(`\n✅ 完成！`);
    console.log(`  - 新创建学生账号: ${newUserCount} 个`);
    console.log(`  - 新创建角色关联: ${newUserRoleCount} 个`);
    console.log(`  - 总用户数: ${users.length}`);
    console.log(`  - 总角色关联数: ${userRoles.length}`);
}

// 执行脚本
fixUserAccounts().catch(error => {
    console.error('执行失败:', error);
    process.exit(1);
});

